const https = require('https'); // 使用 https 模块
const fs = require('fs');
const path = require('path');

// 图片的 URL
const imageUrl = 'https://c-ssl.duitang.com/uploads/blog/202303/15/20230315122323_e3c0f.jpg'; // 确保是 https 协议

// 下载图片并保存到本地
function downloadImage(url, destination) {
  // 创建 https 请求
  https.get(url, (response) => {
    // 检查 HTTP 响应状态码是否为 200 (成功)
    if (response.statusCode !== 200) {
      console.error(`Failed to get image: HTTP status code ${response.statusCode}`);
      return;
    }

    // 创建写入流到本地文件
    const fileStream = fs.createWriteStream(destination);

    // 将响应数据管道到写入流
    response.pipe(fileStream);

    // 监听完成事件
    fileStream.on('finish', () => {
      console.log(`Image downloaded and saved to ${destination}`);
      fileStream.close();
    });

    // 监听错误事件
    fileStream.on('error', (err) => {
      fs.unlink(destination, () => {}); // 删除可能部分写入的文件
      console.error(`Error writing file: ${err.message}`);
    });
  }).on('error', (err) => {
    console.error(`Error making request: ${err.message}`);
  });
}

// 使用示例
const downloadPath = path.join(__dirname, 'downloaded-image.jpg');
downloadImage(imageUrl, downloadPath);